package com.tengju.support.domain.model.rule;

import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@NoArgsConstructor
public class TimeCondition extends Condition {

    List<LocalDateTime> factors;

    Operation operation;

    String field;


    public List<LocalDateTime> getFactors() {
        return factors;
    }

    public Operation getOperation() {
        return operation;
    }

    public String getField() {
        return field;
    }

    public TimeCondition(String field, List<String> factors, Operation operation) {
        this.field = field;
        if (!CollectionUtils.isEmpty(factors)) {
            this.factors = factors.stream()
                    .map(timeVal -> LocalDateTime.parse(timeVal, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .collect(Collectors.toList());
        }
        this.operation = operation;
    }


    @Override
    public boolean evaluate(MetaInfo metaInfo) {

        if (!compareNow() && CollectionUtils.isEmpty(factors)) {
            return false;
        }

        //反射 获取字段值
        Object content = super.fieldData(metaInfo,field);

        if (StringUtils.isEmpty(content)) {
            return false;
        }

        LocalDateTime fact = (LocalDateTime) content;

        switch (operation) {

            case IS_TODAY:
                return fact.toLocalDate().isEqual(LocalDate.now());
            case IS_NOT_TODAY:
                return !fact.toLocalDate().isEqual(LocalDate.now());
            default:
                return false;
        }
    }

    private boolean compareNow() {
        return Operation.IS_TODAY == operation||
                Operation.IS_NOT_TODAY == operation;
    }
}

